package com.ton.system.service;

import com.hai.admin.table.service.ITableDataService;
import com.ton.config.Perm;
import com.ton.system.entity.AdminPermission;
import com.ton.utils.SqlArgUtil;
import com.kypj.frame.db.MyTemplate;
import com.kypj.frame.db.Pager;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AdminPermissionService implements ITableDataService<AdminPermission> {
    @Resource
    private MyTemplate myTemplate;

    @Override
    public List<AdminPermission> listData(Pager pager, AdminPermission vo, String requestSource) {
        String search = SqlArgUtil.like(vo.getKeyword());
        String countSql = "#perm_name like ? or #permission like ?";
        int count = myTemplate.myCountAppendWhereCondition(AdminPermission.class, countSql, search, search);
        pager.setCount(count);
        String sql = "#perm_name like ? or #permission like ? order by ifnull(parent_id,id) limit ?,?";
        return myTemplate.myQueryForListAppendWhereCondition(AdminPermission.class, sql, search, search, pager.limitStart(), pager.limitEnd());
    }

    @Override
    public void save(AdminPermission object, String requestSource) {
        if (object.getPermission().indexOf(Perm.super_permission) >= 0) {
            throw new RuntimeException("不允许权限内容中包含：" + Perm.super_permission);
        }
        myTemplate.mySaveObject(object);
    }

    @Override
    public void update(AdminPermission object, String requestSource) {
        if (object.getId() == 1) {
            throw new RuntimeException("超级管理员权限不允许编辑");
        }
        myTemplate.myUpdateObjectSelective(object);
    }

    @Override
    public void deleteObject(AdminPermission object, String requestSource) {
        if (object.getId() == 1) {
            throw new RuntimeException("超级管理员权限不允许编辑");
        }
        myTemplate.myDelete(object);
    }
}
